package com.bigfans.framework.redis;

import java.io.IOException;

import lombok.Data;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Data
public class JedisConnectionFactory {

	private volatile JedisPool jedisPool = null;
	private JedisCluster cluster = null;
	
	private String host;
	private int port;
	private String auth;
	private int max_idle;
	private int timeout;
	private boolean test_on_borrow;
	private int defaultDbIndex = 0;

	public JedisConnection getConnection() {
		if (jedisPool == null) {
			synchronized (this) {
				if (jedisPool == null) {
					JedisPoolConfig config = new JedisPoolConfig();
					config.setMaxIdle(max_idle);
					config.setTestOnBorrow(test_on_borrow);
					jedisPool = new JedisPool(config, host, port,timeout);
				}
			}
		}
		Jedis jedis = jedisPool.getResource();
		return new JedisConnection(jedis , defaultDbIndex);
	}

	public void close() {
		if (jedisPool != null) {
			synchronized (this) {
				if (jedisPool != null) {
					jedisPool.close();
					jedisPool = null;
				}
			}
		}
		if (cluster != null) {
			try {
				cluster.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

//	public JedisCluster getJedisFromCluster() {
//		if (cluster != null) {
//			Set<HostAndPort> nodes = new HashSet<HostAndPort>();
//			nodes.add(new HostAndPort("192.168.25.3", 7001));
//			nodes.add(new HostAndPort("192.168.25.3", 7002));
//			nodes.add(new HostAndPort("192.168.25.3", 7003));
//			nodes.add(new HostAndPort("192.168.25.3", 7004));
//			nodes.add(new HostAndPort("192.168.25.3", 7005));
//			cluster = new JedisCluster(nodes);
//		}
//		return cluster;
//	}
	
}
